<template>
  <div class="ai--wrap">
    <div class="ai--left">
      <div
        :class="['ai-item', { active: predict == item.id }]"
        v-for="item in aiResArr"
        :key="item.id"
      >
        <span class="item--title">{{ item.value }}</span>
        <span class="item--value" v-show="predict == item.id">{{predictVal}}%</span>
      </div>
      <div class="left--loading" v-show="loading">
        <a-spin tip="诊断中..."> </a-spin>
      </div>
    </div>
    <div class="ai--right">
      <div class="img--box">
        <img :src="imgSrc" alt="" />
      </div>
      <div class="upload--box">
        <a-upload-dragger
          v-model:fileList="fileList"
          name="file"
          :customRequest="onCustomRequest"
          :beforeUpload="beforeUpload"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined></InboxOutlined>
          </p>
          <p class="ant-upload-text">点击或拖动文件至此区域进行上传</p>
          <p class="ant-upload-hint">支持格式:jpg/png</p>
        </a-upload-dragger>
      </div>
    </div>
  </div>
</template>

<script>
import { InboxOutlined } from "@ant-design/icons-vue";
import { aiResArr } from "@/utils";
import { uploadImage } from "@/api"
export default {
  name: "Ai",
  components: { InboxOutlined },
  data() {
    return {
      fileList: [],
      aiResArr: aiResArr,
      aiRes: "",
      imgSrc: "",
      loading: false,
      predict:null,
      predictVal:null
    };
  },
  methods: {
    async onCustomRequest(options) {
      this.loading = true;
      const { file, onSuccess, onError } = options;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.imgSrc = reader.result;
        onSuccess && onSuccess("ok");
        this.uploadImg(reader.result.split(",").pop());
      };
      reader.onerror = (err) => {
        this.$message.error("文件读取失败");
        onError && onError(err);
      };
    },
    async uploadImg(data){
      try {
        const formData = new FormData();
        formData.append("image", data);
        const res = await uploadImage("http://127.0.0.1:3010", formData);
        console.log(res);
        if(res.success){
          this.loading = false;
          this.predict = res.predict;
          this.predictVal =  Number(res.value * 100).toFixed(4);
        }
      }catch(err){
        this.loading = false;
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("仅支持上传JPG或PNG格式图片！");
      }
      return isJpgOrPng;
    },
  },
};
</script>

<style scoped lang="less">
@import "@/assets/ai.less";
</style>
